(function(win, doc, objName) {
  // 定义全局对象
  function Obj() {};
  Obj.prototype = {
    /**
     * 简单cookie获取与设置
     * @param  {string} name  cookie设置或获取
     * @param  {string} value 设置cookie的值
     * @param  {string} op 设置cookie的参数
     */
    cookie: function(name, value, op) {
      // 变量获取
      var op = op || {},
        expires = '',
        d = new Date();
      if (typeof value != 'undefined') {
        if (value === null) {
          op.expires = -1
        }; //删除
        if (op.expires && (typeof op.expires == "number" || op.expires.toUTCString)) {
          if (typeof op.expires == "number") {
            d.setTime(d.getTime() + (op.expires * 36e5))
          } // 以小时为单位
          else {
            d = op.expires
          }
          expires = "; expires=" + d.toUTCString();
        }
        doc.cookie = [name, "=", encodeURIComponent(value), expires, op.path ? ("; path=" + op.path) : "", op.domain ? ("; domain=" + op.domain) : "", op.secure ? "; secure" : ""].join('');
      } else {
        return decodeURIComponent(doc.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + name + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null
      }
    },
    /**
     * loadjs 同步或异步方式加载js文件 opt:
     * @param  {[type]} src 加载js地址
     * @param  {[type]} opt  {charset,id,data,async:true} 默认同步输出
     */
    loadjs: function(src, opt) {
      opt = opt || {};
      if (opt.async) {
        var obj = doc.createElement('script');
        obj.src = src;
        obj.async = true;
        obj.type = 'text/javascript';
        if (opt.charset) {
          obj.charset = opt.charset;
        }
        if (opt.data) {
          obj.data = opt.data;
        }
        if (opt.id) {
          obj.id = opt.id;
        }
        (doc.head || doc.getElementsByTagName('head')[0] || doc.docElement).appendChild(obj);
      } else {
        doc.write('<script src="' + src + '"' + (opt.charset ? ' charset="' + opt.charset + '"' : '') + (opt.data ? ' data="' + opt.data + '"' : '') + (opt.id ? ' id="' + opt.id + '"' : '') + '></script>');
      }
    },
    topBannerStyle: function(height) {
      height = height || 100;
      $('head').append('<style>.topBannerBox{width:100%;z-index:9999;background:#292929;height:' + height / 2 + 'px;}.topBannerBox .topBannerBD{position:fixed;top:0;width:100%;height:' + height / 2 + 'px;background:rgba(0,0,0,.75);}.topBannerBox .topBannerAnim{-webkit-transform:translateY(0);transform:translateY(0);-webkit-transition:all .5s cubic-bezier(.19,1,.22,1);transition:all .5s cubic-bezier(.19,1,.22,1);z-index:9999;}.topBannerBox .topBannerAnimHidden{-webkit-transform:translateY(-101%);transform:translateY(-101%);-webkit-transition:all .3s cubic-bezier(.55,.055,.675,.19);transition:all .3s cubic-bezier(.55,.055,.675,.19);z-index:9999;}.topBannerBox .close{position:absolute;top:0;right:0;width:24px;height:' + height / 2 + 'px;line-height:' + height / 2 + 'px;color:#999;padding:0;background:none;font-size:24px;font-family:SimSun,Tahoma,arial,SimHei,sans-serif;text-align:center;text-decoration:none;z-index:9999;}[data-dpr="2"] .topBannerBox,[data-dpr="2"] .topBannerBox. topBannerBD{height:' + height + 'px}[data-dpr="3"] .topBannerBox,[data-dpr="3"] .topBannerBox. topBannerBD{height:' + height * 1.5 + 'px}[data-dpr="2"] .topBannerBox .close{width:48px;height:' + height + 'px;line-height:' + height + 'px;}[data-dpr="3"] .topBannerBox .close{width:72px;height:' + height * 1.5 + 'px;;line-height:' + height * 1.5 + 'px;}.topBannerBox,.topBannerBox *,.topBannerBox:after,.topBannerBox:after,.topBannerBox:before,.topBannerBox:before{box-sizing:border-box}.topBannerBox .txtBox,.topBannerBox .open{position:absolute;top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.topBannerBox .open{right:32px;display:inline-block;width:88px;line-height:30px;border-radius:3px;font-size:12px;text-decoration:none;color:#fff;text-align:center;white-space:nowrap;background:#ff424b}.topBannerBox .txtBox{left:5px}.topBannerBox .txtBoxTxt{color:#fff;font-size:12px; margin:0 0 0 8px;}.topBannerBox .logoTxt{margin:0 0 2px 0;color:#f9f978;font-size:20px;line-height:1;font-weight:400}.topBannerBox .jisu{color:#a7f96f}.topBannerBox .noad{color:#ffcec5}.topBannerBox .cache{color:#9af5bf}@media screen and (max-width:320px){.topBannerBox .logoTxt{font-size:16px}}@media screen and (max-width:375px){.topBannerBox .logoTxt{font-size:16px}}</style>')
    },
    zymkTopBannerStyle: function(){
      $('head').append('<style>.topBannerBox{width:100%;z-index:9999;box-sizing:border-box;height:1.33333rem;}.topBannerBox .topBannerBD{position:fixed;top:0;width:100%;height:1.33333rem;background:rgba(0,0,0,0.75)}.topBannerBox .topBannerAnim{-webkit-transform:translateY(0);transform:translateY(0);transition:all 0.5s cubic-bezier(0.19, 1, 0.22, 1);z-index:9999}.topBannerBox .topBannerAnimHidden{-webkit-transform:translateY(-101%);transform:translateY(-101%);transition:all 0.3s cubic-bezier(0.55, 0.055, 0.675, 0.19);z-index:9999}.topBannerBox .close{position:absolute;top:0;right:0;width:.64rem;height:1.33333rem;line-height:1.33333rem;color:#999;padding:0;background:none;font-size:.64rem;font-family:SimSun, Tahoma, arial, SimHei, sans-serif;text-align:center;text-decoration:none;z-index:9999}.topBannerBox .txtBox,.topBannerBox .open{position:absolute;top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.topBannerBox .open{right:.85333rem;display:inline-block;width:2.34667rem;line-height:.8rem;border-radius:.08rem;font-size:.32rem;text-decoration:none;color:#fff;text-align:center;white-space:nowrap;background:#ff424b}.topBannerBox .txtBox{left:.13333rem}.topBannerBox .txtBoxTxt{color:#fff;font-size:.32rem;margin:0 0 0 .21333rem}.topBannerBox .logoTxt{margin:0 0 .05333rem 0;color:#f9f978;font-size:.53333rem;line-height:1;font-weight:400}.topBannerBox .jisu{color:#a7f96f}.topBannerBox .noad{color:#ffcec5}.topBannerBox .cache{color:#9af5bf}</style>')
    },
    addBanner: function(content, opt) {
      opt = $.extend({
        height: 100,
        defaltEvent: true
      }, opt);
      if(opt.host === 'zymk'){
        this.zymkTopBannerStyle();
      }else{
        this.topBannerStyle(opt.height); //设置样式
      }
      $('body').prepend('<div class="topBannerBox"><div class="topBannerBD topBannerAnim" style="display: block !important;"><a href="javascript:void(0)" class="close">&times;</a>' + content + '</div></div>');

      // 添加事件操作
      this.hiddenBanner(opt.expires); //默认设置关闭后失效时间为关闭阅览器
      if (opt.defaltEvent) {
        this.topBannerAnim(opt.scrollHeight ? opt.scrollHeight : opt.height); //默认执行
      }
    },
    hiddenBanner: function(expires) {
      var that = this;
      $('.topBannerBox .close').click(function(event) {
        event.stopPropagation();
        event.preventDefault();
        that.cookie('topBanner2', true, expires ? {
          expires: expires
        } : {
          expires: 0.1
        }); // 默认过期时间为1小时
        $('.topBannerBox').remove();
      })
    },
    topBannerAnim: function(dis) {
      $(win).scroll(function() {
        var obj = $('.topBannerBox .topBannerBD');
        if ($(win).scrollTop() > dis) {
          obj.attr('class', 'topBannerBD topBannerAnimHidden')
        } else {
          obj.attr('class', 'topBannerBD topBannerAnim')
        }
      })
    },
    getConfig: function() {
      var baseData = {
        kanman: {
          appname: '看漫画',
          linkedMEKey: 'a0a360c7a4cd37b7dd82459955c879e2',
          ckey: 'CK1358783039325',
          pkgname: 'com.wbxm.icartoon',
          scheme_Adr: 'tkanmanapp',
          isLocalURL: true
        },
        iyouman: {
          appname: '爱优漫',
          linkedMEKey: 'a0a360c7a4cd37b7dd82459955c879e2',
          ckey: 'CK1358783561013',
          pkgname: 'com.wbxm.icartoon',
          scheme_Adr: 'tkanmanapp',
          isLocalURL: true
        },
        shenmanhua: {
          appname: '看漫画',
          linkedMEKey: 'a0a360c7a4cd37b7dd82459955c879e2',
          ckey: 'CK1358783076176',
          pkgname: 'com.wbxm.icartoon',
          scheme_Adr: 'tkanmanapp',
          isLocalURL: true
        },
        douluodalu3: {
          appname: '看漫画',
          linkedMEKey: 'a0a360c7a4cd37b7dd82459955c879e2',
          ckey: 'CK1360783640659',
          pkgname: 'com.wbxm.icartoon',
          scheme_Adr: 'tkanmanapp',
          isLocalURL: true
        },
        manhuatai: {
          appname: '漫画台',
          linkedMEKey: '30295716ccff68e4c178c9b70f62f04d',
          ckey: 'CK1358783372301',
          pkgname: 'com.comic.manhuatai',
          scheme_Adr: 'tmanhuataiapp',
          isLocalURL: true
        },
        zymk: {
          appname: '知音漫客',
          linkedMEKey: 'dd3dccbc8f480da1e37e8b601f7714c8',
          ckey: 'CK1353950509167',
          pkgname: 'cn.zymk.comic',
          scheme_Adr: 'zymkapp',
          isLocalURL: true
        }
      };
      var host = location.host.replace(/([a-z]{1,6}\.)?(.+)(\.[a-z]{2,4})$/, '$2');
      if(!baseData[host]) host = 'kanman';
      var url = 'http://a.app.qq.com/o/simple.jsp?pkgname=' + baseData[host].pkgname + '&ckey=' + baseData[host].ckey;
      var gobalInfo = win.gobal_info || {};
      var scheme_Adr = '';
      if(host === 'zymk'){
        // 获取全局的漫画信息
        var match = location.pathname.match(/^\/\d+/g);
        gobalInfo.comic_id = match?location.pathname.match(/^\/\d+/g)[0].substr(1):''; //获取到漫画的目录id
        scheme_Adr = baseData[host].scheme_Adr + '://goto?page=' + (gobalInfo.comic_id?'dir':'index') + '&comic_id=' + gobalInfo.comic_id;
      }else{
        scheme_Adr = baseData[host].scheme_Adr + '://' + location.hostname.replace('m.','www.')+ '/open?id=' + gobalInfo.comic_id;
      }
      if (!gobalInfo.comic_id){
        gobalInfo.page = 'index';
      } else {
        gobalInfo.page = 'dir';
      }
      return {
        host: host,
        localURL: url,
        isLocalURL: baseData[host].isLocalURL || false,
        scheme_Adr: scheme_Adr,
        appname: baseData[host].appname,
        key: baseData[host].linkedMEKey,
        // type: 'test', // 表示现在使用线上模式,如果填写"test", 表示测试模式.【可选】
        // feature: "功能名称", // 自定义深度链接功能，多个用逗号分隔，【可选】
        // stage: "阶段名称", // 自定义深度链接阶段，多个用逗号分隔，【可选】
        // channel: host, // 自定义深度链接渠道，多个用逗号分隔，【可选】
        // tags: "标签名称", // 自定义深度链接标签，多个用逗号分隔，【可选】
        // ios_custom_url: baseData[host].iosUrl || url, // 自定义iOS平台下App的下载地址，如果是AppStore的下载地址可以不用填写，【可选】
        // android_custom_url: baseData[host].androidUrl || url, // 自定义安卓平台下App的下载地址，【可选】
        params: JSON.stringify(gobalInfo) // 注意单引号和双引号的位置
      }
    },
    topBannerDom: function(data) {
      var _this = this;
      if (_this.cookie('topBanner2')) return;
      var str = '<span class="jisu">极速</span> <span class="noad">无广告</span> <span class="cache">离线缓存</span>';
      if (data.host === 'zymk') {
        str ='<span class="jisu">人气漫画阅读且永久免费</span> <span class="noad">无广告</span>';
      }
      _this.addBanner('<div class="txtBox"><h2 class="logoTxt">《'+ data.appname +'》APP</h2><p class="txtBoxTxt">'+ str +'</p></div><a id="schemeOpen" class="open">打开APP阅读</a><div id="linkedmeBox"></div>', {scrollHeight: 300, host: data.host});
    },
    clickLoadLinkedme(data){
      var _this = this;
      if(data.isLocalURL) {
        _this.openScheme();
        return false;
      }
      _this.loadjs('https://lkme.cc/js/linkedme.min.js', {async:true});
      data = data || {type: 'live'};
      var timer = null;
      timer = setInterval(function() {
        if (typeof linkedme !== 'undefined') {
          clearInterval(timer);
          linkedme.init(data.key, {
            type: data.type
          }, null);

          linkedme.link(data, function(err, res) {
            if(!res.url) {
              _this.openScheme()
            }else{
              $('#linkedmeBox').html('<a class="linkedme" style="display:none" href="'+ res.url +'"></a>');
            }
          }, true);
        }
      }, 25);
    },
    openScheme: function(){
      $('#linkedmeBox').html('<span class="openScheme" onclick="'+objName+'.schemeFn()"></span>');
      $('.openScheme').click();
    },
    schemeFn: function() {
      var tmpData = this.getConfig();
      var data = {
        scheme_Adr: tmpData.scheme_Adr,
        url: tmpData.localURL,
        timeout: 600
      };
      var UA = navigator.userAgent.toLowerCase();
      if(UA.match(/(iPhone|iPod|iPad);?/i)){
        //抛出schemes,打开app对应页面
        win.location.href = data.scheme_Adr;
        //由于部分ios中打开app后，WAP页面会被挂起，定时器不会被执行。因此可以做下优化：
        //WAP页重新被聚焦后，如果超过1s，认为APP被打开了，重新聚焦时就不必再跳转到APP下载页
        var startTime = Date.now();
        var delayTime = /safari/.test(UA)?3000:1000;
        var timer = setInterval(function () {
          var endTime = Date.now();
          if (endTime - startTime > delayTime) {
            clearInterval(timer);
            win.location.href = data.url;
          }
        }, 25);
      }else{
        // 如果用户已经安装了应用 抛出schemes,打开app对应页面
        var ifr = doc.createElement('iframe');
        ifr.style.display = 'none';
        doc.body.appendChild(ifr);
        ifr.src = data.scheme_Adr;
        //跳转下载页
        setTimeout(function () {
          win.location.href = data.url;
        }, data.timeout);
      }
    },
    init: function() {
      var _this = this;
      var data = this.getConfig();
      _this.topBannerDom(data);
      $('#schemeOpen').click(function(){
        _this.clickLoadLinkedme(data);
      });
    }
  };
  win[objName] = new Obj(); // 暴露的全局对象名称
})(window, document, 'topBanner');
topBanner.init();
